<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise-2</title>
</head>
<body>
<hr>
<div>

  问题:<input id="question">
</div>

<div>
  答案：<span id="answer"></span>

</div>
<hr>
</body>
<script>


  let question= document.getElementById('question');
  question.onkeyup = function (){


    let txtQuestion = this.value;

    let answer = document.getElementById('answer');
    answer.innerText ='waiting...';
    //getAnswer1(txtQuestion);

  /*  getAnswer2(txtQuestion,function (answer){
      answer.innerText = answer;
    })*/


    getAnswer3(txtQuestion).then((ans)=>{
      answer.innerText = ans;
    })

  }


  /**
   *  传统的异步
   *   参数列表
   *       输入参数  --- question
   *      回调函数   --- success 等待计算结果 并处理计算结果
   * */
  function getAnswer2(question,success){
    let answer =  'this is a answer for ' + question;

    setTimeout(function (){
      success(answer)
    },2000)

  }


  /**
   *   参数列表
   *      输入参数
   *      在此处省略/没有回到函数
   *    new  promise
   *         resolve 给使用提供 then
   * */
  function getAnswer3(question){
    let answer =  'this is a answer for ' + question;

    return new Promise((resolve,reject)=>{
      setTimeout(function (){
         resolve(answer);
      },2000)
    })
  }

  /**
   *  resolve 负责输出 回调函数 需要的数据
   *  reject  负责出错时候的处理，相当于 java -try catch 中 catch中的内容
   * */
  let commonPromise = new Promise((resolve,reject)=>{

      resolve('hello')
  })

  commonPromise.then((res)=>console.log(res));


  let foo = (innerParam)=>{

      let result = 'this is a result for ' +  innerParam;

      return new Promise((resolve)=>{

          resolve(result);
      })
  }


  foo('test').then((res)=>{
      console.log(res);
  })
</script>
</html>